﻿using System;
using System.Collections.Generic;
using UnityEngine;

public class NewTextureController:MonoBehaviour
{
    static NewTextureController _instance;
    public static NewTextureController instance
    {
        get
        {
            if (_instance == null)
                _instance = new GameObject("NewTextureController").AddComponent<NewTextureController>();

            return _instance;
        }
    }
    [System.Serializable]
    public class TexNSpr
    {
        public Texture2D texture;
        public Sprite spr;
    }
    List<TexNSpr> m_NewTexs = new List<TexNSpr>();
    public void AddNewTexture(Texture2D tex, Sprite spr)
    {
        m_NewTexs.Add(new TexNSpr() { texture = tex, spr = spr });
    }

    public bool OnDestroySpr(Sprite spr)
    {
        try
        {
            var ts = m_NewTexs.Find(e => e.spr == spr);
            m_NewTexs.Remove(ts);
            if (ts != null)
            {
                Destroy(ts.texture);
                Destroy(ts.spr);

                return true;
            }
        }
        catch(Exception e)
        {
            GameDebug.LogException(e);
        }
        return false;
    }
    public bool OnDestroyTex(Texture2D tex)
    {
        var ts = m_NewTexs.Find(e => e.texture == tex);
        m_NewTexs.Remove(ts);
        if (ts != null)
        {
            if(ts.texture != null)
                Destroy(ts.texture);
            if (ts.spr != null)
                Destroy(ts.spr);

            return true;
        }
        return false;
    }
    void Awake()
    {
        DontDestroyOnLoad(gameObject);
    }

    void OnDestroy()
    {
        foreach (var ts in m_NewTexs)
        {
            if (ts != null)
            {
                try
                {
                    if (ts.texture != null)
                        DestroyImmediate(ts.texture);
                    if (ts.spr != null)
                        DestroyImmediate(ts.spr);
                }
                catch (Exception e)
                {
                    GameDebug.LogException(e);
                }
            }
        }
        m_NewTexs.Clear();
    }

}

